package com.bookmall.search.web;

import com.alibaba.fastjson.TypeReference;
import com.bookmall.common.constant.MyStatusConstants;
import com.bookmall.common.entity.es.EsModel;
import com.bookmall.search.domain.SearchParam;
import com.bookmall.search.domain.SearchResult;
import com.bookmall.search.domain.vo.BookCategoryVo;
import com.bookmall.search.feign.ProductFeignService;
import com.bookmall.search.service.IElasticSearchService;
import com.ruoyi.common.core.web.domain.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Description:
 * @Author 胡菜鸡
 * @Create 2022-04-08-14:26
 */
@Controller
public class SearchController {
    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private IElasticSearchService elasticSearchService;

    /**
     * 搜索
     * @author 胡菜鸡
     * @date 2022/4/13 15:44
     */
    @GetMapping("/search.html")
    public String search(SearchParam param, Model model){
        SearchResult result = elasticSearchService.search(param);
        for (EsModel esModel : result.getBooks()) {
            List<EsModel.BookImage> defaultImages = esModel.getBookImages().stream()
                    .filter(image -> image.getDefaultImage() == MyStatusConstants.DEFAULT)
                    .collect(Collectors.toList());
            if (defaultImages.size() >= 2) {
                esModel.setFirstImageUrl(defaultImages.get(0).getImageUrl());
                esModel.setSecondImageUrl(defaultImages.get(1).getImageUrl());
            } else if (defaultImages.size() == 1) {
                esModel.setFirstImageUrl(defaultImages.get(0).getImageUrl());
                esModel.setSecondImageUrl(defaultImages.get(0).getImageUrl());
            }
        }
        model.addAttribute("result", result);

        //查出所有的一级分类菜单
//        AjaxResult ajaxResult = productFeignService.listWithTreeForStatus();
//        if(ajaxResult.get(AjaxResult.CODE_TAG).toString().equals("200")){
//            List<BookCategoryVo> categoryList = ajaxResult.getData("data", new TypeReference<List<BookCategoryVo>>() {});
//            model.addAttribute("categories", categoryList);
//        }

        return "search";
    }

    /**
     * 根据书籍id获取书籍详细信息
     * @author 胡菜鸡
     * @date 2022/4/13 15:44
     * @param
     * @return
     */
    @GetMapping("/search/{id}.html")
    @ResponseBody
    public String item(@PathVariable("id") String id){
        return productFeignService.bookItem(id);
    }
}
